<?php

/**
 * @Author: zhibinm (113664000@qq.com)
 * @Date:   2018-04-17 11:19:56 
 * @Copyright:   xuebingsi
 * @Last Modified by:   Zhibinm
 * @Last Modified time: 2018-04-17 14:01:45
 */
/**
* 上传类
*/
class Upload
{
	// 配置项
	public $configs = [
		'type'=>['png','gif','jpg'],
		'maxSize'=>1000000,
		'root_path'=>'./Upload',
		'is_rename'=>true
	];
	//放上传相关信息的
	public $file;
	//放错误信息
	public $errorInfo;
	/**
	 * [__construct 构造函数，初始化配置]
	 * @param array $configs [配置]
	 */
	public function __construct($configs= [])
	{
		$this->configs = array_merge($this->configs,$configs);
	}
	/**
	 * [__get 魔术方式，获取配置]
	 * @param  [type] $name [配置顶]
	 * @return [type]       [配置值]
	 */
	public function __get($name)
	{
		return $this->configs[$name];
	}
	/**
	 * [move 移动文件总进程]
	 * @param  [type] $file [文件信息]
	 * @return [type]       [移动是否成功]
	 */
	public function move($file)
	{
		// var_dump($this->configs);
		// return;
		$this->file = $file;
		if(! $this->checkError()) return false;
		if(!$this->CheckType()) return false;
		if(!$this->checkSize()) return false;
		return $this->save();
	}
	/**
	 * [checkError 检测错误]
	 * @return [type] [是否通过]
	 */
	private function checkError()
	{
		if($this->file['error']<>0){
			switch ($this->file['error']) {
				case 1:
					$this->errorInfo="上传的文件超过了 php.ini 中 upload_max_filesize选项限制的值";
					break;
				case 2:
					$this->errorInfo="传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";
					break;
				case 3:
					$this->errorInfo="文件只有部分被上传";
					break;
				case 4:
					$this->errorInfo="没有文件被上传";
					break;
				case 6:
					$this->errorInfo="找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进";
					break;
				case 7:
					$this->errorInfo="文件写入失败。PHP 5.1.0 引进";
					break;
			}
		}else{
			return true;
		}
	}
	/**
	 * [CheckType 检测类型]
	 * @return [type] [是否通过]
	 */
	private function CheckType()
	{
		$suffix = $this->getSufiix($this->file['name']);

		if(in_array($suffix,$this->type)){
			return true;
		}else{
			$this->errorInfo ="上传的格式不适合条件，允许的类型为".implode(',',$this->type);
			return false;
		}
	}
	/**
	 * [checkSize 检测大小]
	 * @return [type] [是否通过]
	 */
	private function checkSize()
	{

		if($this->file['size']<$this->maxSize){
			return true;
		}else{
			$this->errorInfo ="上传大小受限，允许大小为".$this->maxSize."字节";
			return false;
		}
	}
	/**
	 * [save 挪动文件]
	 * @return [type] [是否通过]
	 */
	private function save()
	{
		// 创建目录
		is_dir($this->root_path) || mkdir($this->root_path);

		//判断是否重命名
		if($this->is_rename){
			$name = uniqid().".".$this->getSufiix($this->file['name']);
		}else{
			$name = $this->file['name'];
		}

		// 移动文件
		$res = move_uploaded_file($this->file['tmp_name'],$this->root_path.'/'.$name);
		
		if(!$res){
 			$this->errorInfo ="移动临时文件失败";
		}else{
			return true;
		}
	}
	/**
	 * [getSufiix 获取后缀]
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 */
	private function getSufiix($name)
	{
		$arr = explode('.', $name);

		return end($arr);
	}
	
}